package com.huiminpay.paymentagent.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.AlipayBean;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import com.huiminpay.paymentagent.api.service.IPayAgentService;
import com.huiminpay.paymentagent.mq.PayProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
@Service
public class PayAgentServiceImpl implements IPayAgentService {
    @Autowired
    PayProducer payProducer;
    @Override
    public PaymentResponseDTO createPayOrderByAliWAP(AliConfigParam aliConfigParam, AlipayBean alipayBean) throws BusinessException {
        try {
            String serverUrl = aliConfigParam.getUrl(),
                    appId = aliConfigParam.getAppId(), format = aliConfigParam.getFormat(),
                    charset = aliConfigParam.getCharest(), signType = aliConfigParam.getSigntype();
            String privateKey = aliConfigParam.getRsaPrivateKey();
            String alipayPublicKey = aliConfigParam.getAlipayPublicKey();
            AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset,
                    alipayPublicKey, signType);

            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            request.setNotifyUrl(aliConfigParam.getNotifyUrl());//异步通知
            request.setReturnUrl(aliConfigParam.getReturnUrl());//同步通知
            // 业务参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", alipayBean.getOutTradeNo());// 订单号
            bizContent.put("total_amount", alipayBean.getTotalAmount());// 订单金额
            bizContent.put("subject", alipayBean.getSubject());// 订单标题
            bizContent.put("product_code", "QUICK_WAP_WAY");
            bizContent.put("timeout_express","10m");//10分钟后关闭订单 m代表分钟 h代表小时 d代表天
            request.setBizContent(bizContent.toString());
            AlipayTradeWapPayResponse alipayTradeWapPayResponse = alipayClient.pageExecute(request);
            // 判断调用成功还是失败
            if(alipayTradeWapPayResponse.isSuccess()){
                String body = alipayTradeWapPayResponse.getBody();

                PaymentResponseDTO paymentResponseDTO = new PaymentResponseDTO();
                paymentResponseDTO.setContent(body);

                // 发送延时消息队列监听订单状态
                paymentResponseDTO.setOutTradeNo(alipayBean.getOutTradeNo());
                paymentResponseDTO.setTradeNo(alipayBean.getOutTradeNo());
                payProducer.payOrderNotice(paymentResponseDTO);
                return paymentResponseDTO;
            }
            throw new BusinessException(CommonErrorCode.E_200242);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_200242);
        }


    }

    @Override
    public PaymentResponseDTO queryAlipayOrderInfo(AliConfigParam aliConfigParam, String tradeNo) throws BusinessException {
        try {
            String serverUrl = aliConfigParam.getUrl(),
                    appId = aliConfigParam.getAppId(), format = aliConfigParam.getFormat(),
                    charset = aliConfigParam.getCharest(), signType = aliConfigParam.getSigntype();
            String privateKey = aliConfigParam.getRsaPrivateKey();
            String alipayPublicKey = aliConfigParam.getAlipayPublicKey();
            AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset,
                    alipayPublicKey, signType);

            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest ();
            // 业务参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", tradeNo);// 订单号

            request.setBizContent(bizContent.toString());
            AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(request);
            // 判断调用成功还是失败
            if(alipayTradeQueryResponse.isSuccess()){
                String body = alipayTradeQueryResponse.getBody();
                System.out.println(body);
                PaymentResponseDTO paymentResponseDTO = new PaymentResponseDTO();
                paymentResponseDTO.setContent(alipayTradeQueryResponse.getTradeStatus());
                paymentResponseDTO.setTradeNo(alipayTradeQueryResponse.getTradeNo());//三方交易号
                //
                String tradeStatus = alipayTradeQueryResponse.getTradeStatus();
                TradeStatus tradeStatus1 = TradeStatus.USERPAYING;
                if(tradeStatus.equals("TRADE_SUCCESS")){
                    tradeStatus1 = TradeStatus.SUCCESS;
                }else if(tradeStatus.equals("TRADE_CLOSED")){
                    tradeStatus1 = TradeStatus.REVOKED;
                }else if(tradeStatus.equals("TRADE_FINISHED")){
                    tradeStatus1 = TradeStatus.SUCCESS;
                }
                paymentResponseDTO.setTradeState(tradeStatus1);
                return paymentResponseDTO;
            }
            log.info("支付返回：{}", JSON.toJSONString(alipayTradeQueryResponse));
            throw new BusinessException(CommonErrorCode.E_200242);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_200242);
        }
    }
}
